<template>
    <div>

        <van-popup v-model="m_show" closeable round :close-on-click-overlay="false" duration="0.2">
            <div class="wrap">
                <div class="title" ref="toPicTitle">{{agreementName}}</div>
                <div class="content" ref="toPicContent">
                    <div v-html="agreementContent" style="white-space:pre-wrap"></div>

                    <div class="footer">
                        <div class="sign-wrap">用户签名：{{customerName}}
                            <img :src="imgSrc" alt="" v-if="imgSrc">
                        </div>
                        <div>日期时间：{{datetime}}</div>
                    </div>

                </div>

                <div class="btn-wrap">
                    <van-checkbox v-if="need_agree" v-model="checked" shape="square" checked-color="#24C373" class="checkbox">已阅读并同意</van-checkbox>

                    <van-button class="btn" color="#24C373" @click="onAgree" :disabled="need_agree && !checked" v-prevent-re-click>{{!need_sign ? '确定' : imgSrc ? '确定提交' : '去签名'}}</van-button>
                </div>

            </div>
        </van-popup>

        <!--显示手写签名-->
        <van-popup v-model="showSignPopup" position="right" @opened="bindShowESign">
            <div class="esign-wrap">
                <div class="esign" ref="esignWrap">
                    <vue-esign
                            v-if="showSign"
                            ref="esign"
                            :width="esignW"
                            :height="esignH"
                            :isCrop="isCrop"
                            :bgColor="bgColor"
                            :lineWidth="lineWidth"
                            :lineColor="lineColor"/>
                </div>
                <div class="btns">
                    <div class="btn-wrap"><van-button color="#24C373" @click="handleGenerate" class="btn">确定签名</van-button></div>
                    <div class="btn-wrap"><van-button color="#24C373" @click="handleReset" class="btn">清空画板</van-button></div>
                    <div class="btn-wrap"><van-button @click="cancelSign" class="btn">取消签名</van-button></div>
                    <!--<img :src="imgSrc" alt="">-->

                </div>
                <!-- <div>
                     <div class="wrap">
                     </div>
                 </div>-->
            </div>
        </van-popup>
        <!--<img :src="agreementImg" alt="">-->
        <!--<img :src="signImg" alt="">-->
    </div>
</template>

<script>
  import {Popup,Checkbox} from 'vant'
  import {preventReClick} from "../../utils/plugins";
  import html2canvas from "html2canvas"
  import { crtTimeFtt} from "../../utils/utils";
  import {fillText,} from "../../utils/img";
  import vueEsign from 'vue-esign';
  import {getLocation} from "../../utils/wx";
  import {mapGeocoder,getAgreement} from "../../request/api";
  import dialog from '@/utils/dialog';
  import {mapState} from 'vuex';

  export default {
    name: "m-agreement",
    components: {
      [Popup.name]: Popup,
      [Checkbox.name]: Checkbox,
      vueEsign
    },
    model: {
      prop: 'show',
      event: 'showEvent'
    },
    watch: {
      show:{
        handler(val){
          this.m_show = val;
          this.checked = false;
          this.datetime = '';
          this.imgSrc = '';
          this.signImg = '';
          this.agreementImg = '';
          this.datetime = crtTimeFtt(new Date(),'YYYY-MM-DD HH:mm');
          this.local = '';
        },
        immediate: true
      },
      m_show(val){
        this.$emit('showEvent',val);
      },

      agreement_id:{
        handler(val){
          val && this.getAgreementData();
        },
        immediate: true
      }
    },

    props: {
      // 显示弹窗
      show: {
        default: false
      },
      // 协议id
      agreement_id: {},
      // 需要勾选同意
      need_agree: {
        default: true
      },
      // 需要签名
      need_sign: {
        default: true
      },
    },
    computed: {
      ...mapState({
        customerName: state => state.user.customerName,
        customerPhone: state => state.user.customerPhone,
      }),
    },
    data(){
      return {
        m_show: true,

        checked: false,
        datetime: '',
        local: '',

        //显示手写签名
        showSignPopup: false,
        esignH: 0,
        esignW: 0,
        lineWidth: 6,
        lineColor: '#000000',
        bgColor: '#fff',
        resultImg: '',
        isCrop: false,
        showSign: false,


        imgSrc:'',
        signImg: '',
        agreementImg: '',

        agreementContent: '',   //协议内容
        agreementName: ''   //协议标题

      }
    },
    methods: {
      toPic(){
        return new Promise(resolve => {
          let div = document.createElement('div'),
            title = this.$refs.toPicTitle.cloneNode(true),
            content = this.$refs.toPicContent.cloneNode(true);
          div.setAttribute("style","padding: 0 15px;width: 335px;display:flex;flex-direction: column;align-items: center;")
          div.appendChild(title)
          div.appendChild(content);
          document.body.appendChild(div); //放到body后面
          html2canvas(div,
            /*{  scale: 1, }*/ // 使用自定义函数计算缩放比例
            ).then(canvas => {
            let imgUrl = canvas.toDataURL("image/png");
            document.body.removeChild(div);
            this.agreementImg = imgUrl;
            resolve(imgUrl)
          });
        })
      },

      // 清空画布
      handleReset () {
        this.$refs.esign.reset()
      },
      // 生成签名的base64图片
      handleGenerate () {
        this.$refs.esign.generate().then(async res => {//res：base64图片地址
          // this.imgSrc = res;
          let local = this.local,
            now = new Date(),
            date = crtTimeFtt(now,'YYYY-MM-DD HH:mm');
          // await this.getLocation().then(name => local = name);
          let opts = [
            {
              content: local,
              font: '20px serif',
              position: {
                bottom: 10,
                left: 10
              }
            },
            {
              content: date,
              font: '26px serif',
              position: {
                bottom: 40,
                left: 10
              }
            },
          ]
          this.addWatermark(res,opts).then(res=>{
            console.log(res);
            this.signImg = res;
            this.showSignPopup = false;


          })
          // console.log(res,base64ImgtoFile(res))
        }).catch(err => {
          console.log('画布没有签字时会执行这里 Not Signned')
          this.$Toast('请签名确认购票。')
        })
      },
      //显示签名
      bindShowESign(){
        let {clientHeight,clientWidth} = this.$refs.esignWrap;
        this.esignH = clientHeight;
        this.esignW = clientWidth;
        this.showSign = true;
      },
      //取消签名-取消购票，发起解锁
      cancelSign(){
        this.showSignPopup = false;
        this.handleReset();
      },

      /**
       * 签名添加水印
       * @param src 签名图片地址base64
       * @param opts 水印参数
       * @return {Promise<any>} 返回已添加水印的签名图片地址base64
       */
      addWatermark(src,opts) {
        return new Promise((resolve,reject) => {
          const img = new Image();
          img.src = src;
          img.setAttribute('crossOrigin', 'Anonymous')
          img.onload = () => {
            let canvas = document.createElement('canvas')
            let context = canvas.getContext('2d')
            /*if (rotate > 45 && rotate <= 135) { // 90 宽高颠倒
              canvas.width = img.height
              canvas.height = img.width
            } else if (rotate > 225 && rotate <= 315) { // 270 宽高颠倒
              canvas.width = img.height
              canvas.height = img.width
            } else {
              canvas.width = img.width
              canvas.height = img.height
            }*/
            let rotate = 270;  //旋转270度
            const {width: originWidth, height: originHeight} = img;
            canvas.width = originHeight;
            canvas.height = originWidth;
            context.clearRect(0, 0, canvas.width, canvas.height)
            context.translate(canvas.width / 2, canvas.height / 2)
            context.rotate(rotate * Math.PI / 180)
            context.translate(-canvas.width / 2, -canvas.height / 2)
            context.drawImage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.height / 2, img.width, img.height)
            context.translate(canvas.width / 2, canvas.height / 2)
            context.rotate(-rotate * Math.PI / 180)
            context.translate(-canvas.width / 2, -canvas.height / 2)
            context.restore();

            this.imgSrc = canvas.toDataURL();

            //添加水印
            fillText(context, opts, originHeight, originWidth);

            let base64 = canvas.toDataURL();
            resolve(base64);

          }
          img.onerror = reject

        })
      },

      getLocation(){
        return new Promise(resolve => {
          this.$Loading();
          getLocation().then(res => {
            let {latitude,longitude} = res;
            if (!latitude || !longitude)return;
            mapGeocoder({
              "key": process.env.NODE_ENV === 'development' ? process.env.VUE_APP_MAPKEY : window.webConfig.webMapKey,
              "location": `${latitude},${longitude}`,
              "get_poi": "",
              "poi_options": "",
              "output": "",
              "callback": ""
            }).then(res =>{
              let {result} = res,
                {city,district} = result.address_component,
                {recommend} = result.formatted_addresses;
              this.local = `${city}·${recommend}`
              resolve(`${city}·${recommend}`);
              this.$toast.clear();
            })
          },err => {
            this.$toast.clear();
            dialog.alert('无法获取您的定位','为记录您的购票位置信息，需要请您到设置中开启定位权限','知道了')
            // resolve('');
          })
        })
      },

      async onAgree(){
        if (!this.need_sign){
          this.$emit('agree',true);
          this.m_show = false;
          return;
        }
        if (!this.imgSrc){
          await this.getLocation();
          this.showSignPopup = true;
          return
        }
        this.toPic().then(url =>{
          let {agreementImg, signImg} = this
          this.$emit('agree',{
            agreementImg,signImg
          });
        })
      },

      // 获取协议
      getAgreementData(){
        getAgreement(this.agreement_id).then(res => {
          if (res.errcode !== 0) return;
          let data = res.row;
          this.agreementContent = data?.[0]?.agreement_content;
          this.agreementName = data?.[0]?.agreement_name;
        })
      }

    }
  }
</script>

<style scoped lang="less">
    .wrap{
        width: 355px;
        display: flex;
        flex-direction: column;
        align-items: center;
        height: 571px;
    }
    .title{
        padding: 15px 15px 10px;
        color: #333333;
        font-size: 17px;
        font-weight: bold;
    }
    .content{
        flex: 1;
        height: 0;
        /*width: 100%;*/
        overflow: auto;
        padding: 0 15px;
        color: #333333;
        line-height: 24px;
        font-size: 15px;
        p{
            margin: 0;
        }
        .bold{
            font-weight: bold;
        }
        /*.content-text{
            width: calc(100% - 2px);
            height: 100%;
            padding: 0 15px;
            box-sizing: border-box;
            border: none;
            resize: none;
        }*/
    }
    .footer{
        padding: 0 0 10px;
        width: 100%;
        font-size: 15px;
        color: #333333;
        box-sizing: border-box;
        font-weight: bold;
        .sign-wrap{
            display: flex;
            align-items: center;
            height: 50px;
            img{
                height: 100%;
            }
        }
    }
    .btn-wrap{
        width: 100%;
        padding: 5px 15px 15px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        align-items: center;
        .checkbox{
            margin-bottom:10px;
            font-size: 14px;
        }
        .btn{
            width: 100%;
        }
    }
    .pic{
        display: none;
    }

    .esign-wrap{
        width: 100vw;
        height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        flex-direction: column;
        .esign{
            flex: 1;
            height: 0;
            width: 100%;
        }
        .btns{
            display: flex;
            align-self: center;
            flex-shrink: 0;
            width: 100%;
            height: 100px;
            .btn-wrap{
                transform: rotate(90deg);
                width: 90px;
                height: 90px;
                .btn{
                    width: 90px;
                }
            }
        }

    }
</style>
